package com.se.service;

import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ConversationService {
    private final Map<String, List<Message>> conversations = new ConcurrentHashMap<>();
    private static final String SYSTEM_PROMPT = "您是一个友好的聊天机器人，请避免在之后的聊天中使用表情";
    private static final int MAX_HISTORY = 10;

    public List<Message> getOrCreateConversation(String sessionID){
        return conversations.computeIfAbsent(sessionID, k ->
                new LinkedList<>(List.of(new SystemMessage(SYSTEM_PROMPT))));
    }

    public List<Message> getOrCreateConversation(String sessionID, String prompt) {
        return conversations.computeIfAbsent(sessionID, k ->
                new LinkedList<>(List.of(new SystemMessage(prompt))));
    }

    public void addUserMessage(String sessionID, String userMessage){
        List<Message> history = getOrCreateConversation(sessionID);
        history.add(new UserMessage(userMessage));

        if(history.size() > MAX_HISTORY * 2) {
            history.subList(1, 3).clear();
        }
    }

    public void addAIResponse(String sessionID, String AIResponse) {
        List<Message> history = getOrCreateConversation(sessionID);
        history.add(new AssistantMessage(AIResponse));
    }

    public void clearConversation(String sessionId) {
        conversations.remove(sessionId);
    }
}
